package com.gc.materialdesign.views;

import com.gc.materialdesign.ResourceTable;
import com.gc.materialdesign.utils.ResUtil;
import com.gc.materialdesign.utils.ShapeUtil;
import com.gc.materialdesign.utils.Utils;

import ohos.agp.components.AttrSet;
import ohos.agp.components.Component;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.render.Canvas;
import ohos.agp.render.Paint;
import ohos.agp.utils.Color;
import ohos.app.Context;
import ohos.multimodalinput.event.TouchEvent;

public class ButtonIcon extends ButtonFloat {
    public ButtonIcon(Context context) {
        this(context, null);
    }

    public ButtonIcon(Context context, AttrSet attrs) {
        this(context, attrs, null);
    }

    public ButtonIcon(Context context, AttrSet attrs, String defStyleAttr) {
        super(context, attrs, defStyleAttr);
        ShapeElement shapeElement =
                ShapeUtil.createCircleDrawable(ResUtil.getColor(context, ResourceTable.Color_transparent));
        setBackground(shapeElement);
        rippleSpeed = Utils.dpToPx(2, context);
        rippleSize = Utils.dpToPx(5, context);
    }

    @Override
    public boolean onTouchEvent(Component component, TouchEvent event) {
        super.onTouchEvent(component, event);
        if (x != -1) {
            x = getWidth() / 2;
            y = getHeight() / 2;
        }
        return true;
    }

    @Override
    public void onDraw(Component component, Canvas canvas) {
        super.onDraw(component, canvas);
        if (x != -1) {
            Paint paint = new Paint();
            paint.setAntiAlias(true);
            paint.setColor(new Color(Color.getIntColor(Utils.argb(makePressColorString()))));
            paint.setAlpha(0.3f);
            canvas.drawCircle(x, y, radius, paint);
            if (radius > getHeight() / rippleSize) {
                radius += rippleSpeed;
            }
            if (radius >= getWidth() / 2 - rippleSpeed) {
                x = -1;
                y = -1;
                radius = getHeight() / rippleSize;
                if (onClickListener != null && clickAfterRipple) {
                    onClickListener.onClick(this);
                }
            }
            getContext().getUITaskDispatcher().asyncDispatch(this::invalidate);
        }
    }

    @Override
    protected String makePressColorString() {
        return backgroundColor;
    }

    public void setBackgroundColor(String color) {
        this.backgroundColor = color;
        if (isEnabled()) {
            beforeBackground = backgroundColor;
        }
    }
}
